package com.intel.factorytest;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.internal.app.LocalePicker;
import com.intel.factorytest.R;
//import com.intel.factorytest.sensors.SensorTest;
import com.intel.factorytest.activity.ServiceTestsMenuActivity;
import com.intel.factorytest.activity.ShowServiceResultActivity;
import com.intel.factorytest.activity.SoftwareInfo_pref;
import com.intel.factorytest.log.LogWriter;
import com.intel.factorytest.util.SDCardUtil;


public class CopyOfFactoryTest extends PreferenceActivity {
    
    private ArrayList<Integer> testFail = new ArrayList<Integer>();
    private int sensorSum = 0;
    private final String TAG = "FactoryTest";
    static final String TEST_SAVE_RESULT_SENSOR = "oms.action.intent.SAVE_RESULT_SENSOR";
    static final String TEST_SAVE_RESULT_SERVICE = "oms.action.intent.SAVE_RESULT_SERVICE";
    private AudioManager mAudioManager;
    private File sampleDir;
    private String Sm_result ="/data/data/com.intel.factorytest/result.txt";
    private String Se_result ="/data/data/com.intel.factorytest/result_s.txt";
    private String Sm_nvm_result ="/data/Linux/Marvell/NVM/result.txt";
    private String Se_nvm_result ="/data/Linux/Marvell/NVM/result_s.txt";
    private String sys_service ="SYSTEM_SERVICE_TEST";
    private String sys_service_for_pcba ="SYSTEM_SERVICE_FOR_PCBA_TEST";
    private String sdcard_config ="SDCARD_CONFIG";
    private TestFileOp mTestFile = new TestFileOp();
    private File  sampleDir1;
    //private IntentFilter filter = null;
    private String mSdPath = "";
    
    private String logFileName;
    
    private static final String MAT_VERSION = "V2.1.3";
    private TextView mMatVersion;
    
    private int widthScreen = 0;
    private int heightScreen = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);Log.e(TAG, "onCreate");
    //set system language to Chinese
        // fix bug : [Bug 148] New: 产线测试工具打开后，整个系统会成为中文
//    if(savedInstanceState != null) {
//        
//        String language = (String)savedInstanceState.getString("chinese","zh");
//        if(!language.equals("other")) {
//            LocalePicker.updateLocale(new Locale("zh","CN"));
//        }
//    } else {Log.e(TAG, "" + savedInstanceState);
//
//        LocalePicker.updateLocale(new Locale("zh","CN"));
//
//    }
        initScreenSize();
        
        addPreferencesFromResource(R.xml.factorytestpref);    
        //filter = new IntentFilter();
        //filter.addAction(TEST_SAVE_RESULT_SENSOR);
        //filter.addAction(TEST_SAVE_RESULT_SERVICE);
        //registerReceiver(mIntentReceiver, filter);
        mMatVersion = new TextView(this);
        mMatVersion.setText(MAT_VERSION);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 80);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        System.out.println("tangjun software info: heightScreen=" + heightScreen + ",bottom margin=" + (heightScreen-500));
        params.setMargins(200, 0, 0, heightScreen - 500);
        getListView().addFooterView(mMatVersion);


        IsFirstStatus(); 
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.unloadSoundEffects();
        Settings.System.putInt(getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED,0);
        Settings.System.putInt(getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING,0);
        setSkipMode();

    } 
    
    private void initScreenSize() {
        // get screen size
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        this.widthScreen = dm.widthPixels;
        this.heightScreen = dm.heightPixels;
        
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);Log.e(TAG, "onSaveInstanceState");
    outState.putString("chinese", "other");

    }


    final BroadcastReceiver plugSDReceiver =  new BroadcastReceiver() {
         
        @Override
        public void onReceive(Context context, Intent intent) {

            Log.i(TAG, "plugSDReceiver onReceive " + intent.getAction());
        
            if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED))
            {
                mSdPath = intent.getData().getPath();
                
            }
            else if(intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED))
            {
                mSdPath = "";
            
            }
            else
            {}
            
            System.out.println("tangjun FactoryTest:: mSdPath=" + mSdPath);
        }
    };


    
    public boolean onPreferenceTreeClick(PreferenceScreen prefScreen, Preference pref)
    {
        switch(pref.getOrder())
        {
            /*
            case 0://ServiceInfoMenu
            {
                Intent i = new Intent(FactoryTest.this,SoftwareInfo.class);
                startActivity(i);
            break;
            }
            */
/*        case 1:
            {
                Intent i = new Intent(FactoryTest.this,SetFactoryTestActivity.class);
                startActivity(i);
            break;
            }*/
            case 0://ServiceTestsMenu
        {
            // 单项测试不需要记log
            LogWriter.disable();
            logFileName = LogWriter.getFileName(LogWriter.LogType_SingleTest);
            
            Intent i = new Intent(CopyOfFactoryTest.this,ServiceTestsMenuActivity.class);
            i.putExtra(sys_service, 0);
            mTestFile.WriteTextFile(1);
            i.putExtra(sdcard_config, "");
            i.putExtra(LogWriter.LogFileNameTag, logFileName);
            startActivity(i);
            break;
        }
        case 1://SysServiceTestsMenu
        {    
            // 整机测试需要记log
            LogWriter.enable();
            logFileName = LogWriter.getFileName(LogWriter.LogType_SystemTest);
            if(mSdPath.equals("")) {
                callShellCommand("mount");
            }
            System.out.println("tangjun sdcard path is 2 " + logFileName);
            Intent i = new Intent(CopyOfFactoryTest.this,ServiceTestsMenuActivity.class);
            i.putExtra(sys_service,1);
            mTestFile.WriteTextFile(0);
            i.putExtra(sdcard_config,mSdPath);
            i.putExtra(LogWriter.LogFileNameTag, logFileName);
            startActivity(i);
            break;
        }
        case 2://SysServiceTestsMenu for PCBA
        {    
            // 板机测试需要记log
            LogWriter.enable();
            logFileName = LogWriter.getFileName(LogWriter.LogType_PcbaTest);
            if(mSdPath.equals("")) {
                callShellCommand("mount");
            }
            System.out.println("tangjun sdcard path is 3 " + logFileName);
            Intent i = new Intent(CopyOfFactoryTest.this,ServiceTestsMenuActivity.class);
            i.putExtra(sys_service,1);
            i.putExtra(sys_service_for_pcba,1);
            i.putExtra(sdcard_config,mSdPath);
            i.putExtra(LogWriter.LogFileNameTag, logFileName);
            mTestFile.WriteTextFile(0);
            startActivity(i);
            break;
        }
/*
        case 4://SensorTest
        {
            Intent i = new Intent(FactoryTest.this,SensorTest.class);
            startActivity(i);
            break;
            }
*/
        case 4://ServiceTestsMenu
            {
                Intent i = new Intent(CopyOfFactoryTest.this,ShowServiceResultActivity.class);
                startActivity(i);
            break;
            }
    /*    case 5://ServiceTestsMenu
            {
                Intent i = new Intent(FactoryTest.this,DeleteServiceResultActivity.class);
                startActivity(i);
            break;
            }*/
            default:
            break;
        }
        return false;        
    }
    
    @Override
    public void onPause() {
        super.onPause();
        //this.unregisterReceiver(mIntentReceiver);
//        unregisterReceiver(sdCardReceiver);
}

    @Override
    public void finish() {
       // unregisterReceiver(mIntentReceiver);
     //   ReadResultFile();
     //   WriteResultFile();
       //   WriteNVMResultFile();
        super.finish();
    }
    
    /**
     * 监听sdcard插拔
     * 
     * 因为内置SDcard无法插拔，所以该BroadcaseReceiver监听的是外部SDcard的状态。
     */
    BroadcastReceiver sdCardReceiver = new BroadcastReceiver() {
        
        private boolean externalStorageCardAvailable = false;
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            System.out.println("tangjun sdCardReceiver: action=" + action);
            String[] storageList = SDCardUtil.getStorageList(CopyOfFactoryTest.this);
            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                externalStorageCardAvailable = true;
            } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
                externalStorageCardAvailable = false;
            }
            
            for (String path : storageList) {
                if (externalStorageCardAvailable) {
                    if (path.contains("sdcard1")) {
                        System.out.println("tangjun sdCardReceiver: sdcar1 " + "path=" + path);
                        LogWriter.initLogsDir(path);
                        break;
                    }
                } else {
                    if (path.contains("emulated")) {
                        System.out.println("tangjun sdCardReceiver: emulated " + "path=" + path);
                        LogWriter.initLogsDir(path);
                        break;
                    }
                }
            }
        }
    };


    protected void onResume() {
        super.onResume();
        //registerReceiver(mIntentReceiver, filter);
        
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
//        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
//        filter.addDataScheme("file");
//        registerReceiver(plugSDReceiver, filter);

//        IntentFilter filter1 = new IntentFilter();
//        filter1.addAction(Intent.ACTION_MEDIA_MOUNTED);
//        filter1.addAction(Intent.ACTION_MEDIA_EJECT);
//        filter1.addDataScheme("file");
//        registerReceiver(sdCardReceiver, filter1);
    }
   
    private void WriteResultFile() {

        String fileName="/dev/block/mmcblk0p2";    
        try    
        {    
            DataOutputStream out=new DataOutputStream(    
                    new BufferedOutputStream(    
                        new FileOutputStream(fileName)));    
                out.writeInt(testFail.size());    
                out.writeInt(sensorSum);
            Log.e(TAG,"size = "+testFail.size()+"sensor ="+sensorSum);
            for (int i = 0 ;i< testFail.size();i++) {
                out.writeInt(testFail.get(i));    
                Log.e(TAG,"WriteResultFile i="+i+"value ="+testFail.get(i));
            }
            out.close();    
        } catch (IOException e)    
        {    
            e.printStackTrace();    
        }   
    }
    private void ReadResultFile() {
        BufferedReader reader=null;
        BufferedReader readerSensor=null;
        String s=null;
        testFail.clear();
        int serviceNum = 0;
        try {
            reader = new BufferedReader(new FileReader(Sm_result));
            while (reader!=null && (s = reader.readLine()) != null) {
                testFail.add(Integer.valueOf(s));
    //            Log.e(TAG,"**** ="+Integer.valueOf(s));
            }        
            serviceNum = testFail.size();
            readerSensor = new BufferedReader(new FileReader(Se_result));
            while (readerSensor != null && (s = readerSensor.readLine()) != null) {
                testFail.add(Integer.valueOf(s));
    //            Log.e(TAG,"***111 ="+Integer.valueOf(s));
            }        
            sensorSum = testFail.size()-serviceNum;
            Log.e(TAG,"sensorSum === "+sensorSum+"serviceNum = "+serviceNum+"size ="+testFail.size());
        } catch (IOException e) {
            Log.e(TAG,"read  result failed");
        }finally{
            try {
                if (reader!=null)
                    reader.close();
                if (readerSensor!=null)
                    readerSensor.close();
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();             
        Log.e(TAG,"action is "+action);
             if (action.equals(TEST_SAVE_RESULT_SENSOR) || action.equals(TEST_SAVE_RESULT_SERVICE)) {
           //  ReadResultFile();
           //  WriteResultFile(); 
          //     WriteNVMResultFile();
            } 
        }
    };
    public void WriteTextFile() 
        {               
            String fileName="/dev/block/mmcblk0p2";
        int value = 0;
        int sum  = 0;
            int mSensorNum = 0;
        
            String isSensor = null;
        BufferedWriter writer=null;
        BufferedWriter writer_s=null;
        
        try                 
            {       
             DataInputStream  in=new DataInputStream(

                                   new BufferedInputStream(
                                   new FileInputStream(fileName)));
        if (in == null) {
            return;
        }
        sum  = in.readInt();
        mSensorNum = in.readInt(); 
        Log.e(TAG,"^^^^^^^^^^^^^^sum ="+sum+"mSensorNum ="+mSensorNum);
        if (sum > mSensorNum) {
            writer = new BufferedWriter(new FileWriter(Sm_result));
        }
        for (int i =0;i<(sum-mSensorNum);i++) {
            value = in.readInt();
            Log.e(TAG,"readMethod1  res ="+value);    
            writer.write(Integer.toString(value));
            writer.newLine();
            writer.flush();
        }

        if (mSensorNum!=0) {
            writer_s = new BufferedWriter(new FileWriter(Se_result));
        }
        for (int i =0;i<mSensorNum;i++) {
            value = in.readInt();
            writer_s.write(Integer.toString(value));
            writer_s.newLine();
            writer_s.flush();
        }

                in.close();      
        if (writer != null) {
            writer.close();
        }
        if (writer_s != null) {
            writer_s.close();
        }
        } catch (Exception e) 
            {  
                e.printStackTrace();      
            }      
        }
    private void setSkipMode() {
        try {
            sampleDir = new File("/data/data/com.intel.factorytest/setmode.txt");
            //    sampleFile = File.createTempFile(SAMPLE_PREFIX, extension, sampleDir);
            if (!sampleDir.exists())    
                sampleDir.createNewFile();
        } catch (IOException e) {
            Log.d(TAG,"startRecording 11");
        }
    }

    private void WriteNVMResultFile() {
        callShellCommand("cp " + Sm_result + " " + Sm_nvm_result);    
        callShellCommand("cp " + Se_result + " " + Se_nvm_result);    
    }

    public void NvmToTextFile() { 
        callShellCommand("cp " + Sm_nvm_result + " " + Sm_result);    
        callShellCommand("cp " + Se_nvm_result + " " + Se_result);    
    }

    private void callShellCommand(String cmd){
        Log.e(TAG,"########### cmd ="+cmd);
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"sh","-c",cmd});
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String tmp = "";
            while((tmp=br.readLine())!=null){
                Log.i("yjc",tmp);
                if(tmp.contains("fat")) {
                    String[] tmpStrs = tmp.split(" ");
                    mSdPath = tmpStrs[1];

                }
            }
            br.close();

            InputStream eis = p.getErrorStream();
            InputStreamReader eisr = new InputStreamReader(eis);
            BufferedReader ebr = new BufferedReader(eisr);

            while((tmp=ebr.readLine())!=null){
                Log.e("yjc",tmp);
            }
            ebr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private void IsFirstStatus () {
        sampleDir = new File(Sm_result);
        sampleDir1 = new File(Se_result);
        if ((sampleDir == null || !sampleDir.exists())) {
            callShellCommand("cp "+Sm_nvm_result+ " " + Sm_result);    
        }
        if (( sampleDir1 == null || !sampleDir1.exists())) {
            callShellCommand("cp "+Se_nvm_result+ " " +Se_result);    
        }
    }
}
